enable_module = False
try:
    from paramiko import SSHClient
    enable_module = True
except ImportError:
    pass

if enable_module:
    import os
    from pyurl.url import BaseRemoteURL, scheme_registry
    from pyurl.connection import Connection
    
    class SFTPConnection(Connection):
        def __init__(self):
            self.client = None
            self.sftp = None
        
        def open(self, url):
            self.client = SSHClient()
            self.client.load_system_host_keys()
            self.client.connect(url.hostname, url.port or 22, url.username, url.password)
            self.sftp = self.client.open_sftp()
        
        def is_open(self):
            return self.client is not None
        
        def close(self):
            if self.client:
                self.client.close()
                self.client = None
                self.sftp = None
        
        def exists(self, path):
            try:
                self.sftp.stat(path[1:])
            except IOError, e:
                return False
            return True
            
        def open_file(self, path, mode):
            return self.sftp.file(path[1:], mode)
        
        def close(self):
            Connection.close(self)
            self.client.close()
    
    class SFTPURL(BaseRemoteURL):
        _scheme = "sftp"
        _connection_type = SFTPConnection
        
    scheme_registry.register(SFTPURL)